#include "password.h"
#include <string.h>

// 密码数据存储区
static PasswordData passwords[MAX_PASSWORD_COUNT];
static uint16_t passwordCount = 0;

// 密码管理初始化
SystemStatus PWD_Init(void)
{
    // 清空密码数据
    memset(passwords, 0, sizeof(passwords));
    passwordCount = 0;
    
    return SYSTEM_OK;
}

// 添加密码
SystemStatus PWD_Add(const uint8_t *password, uint8_t length, uint16_t *id)
{
    if (passwordCount >= MAX_PASSWORD_COUNT) {
        return SYSTEM_FULL;
    }
    
    if (length > MAX_PASSWORD_LENGTH) {
        return SYSTEM_ERROR;
    }
    
    // 查找空闲位置
    uint16_t freeIndex;
    for (freeIndex = 0; freeIndex < MAX_PASSWORD_COUNT; freeIndex++) {
        if (!passwords[freeIndex].valid) {
            break;
        }
    }
    
    // 保存密码数据
    passwords[freeIndex].id = freeIndex;
    memcpy(passwords[freeIndex].password, password, length);
    passwords[freeIndex].length = length;
    passwords[freeIndex].privilege = 1;  // 默认普通用户权限
    passwords[freeIndex].register_time = 0;  // TODO: 添加实时时钟支持
    passwords[freeIndex].valid = true;
    
    *id = freeIndex;
    passwordCount++;
    
    return SYSTEM_OK;
}

// 删除密码
SystemStatus PWD_Delete(uint16_t id)
{
    if (id >= MAX_PASSWORD_COUNT || !passwords[id].valid) {
        return SYSTEM_NOT_FOUND;
    }
    
    // 清除密码数据
    memset(&passwords[id], 0, sizeof(PasswordData));
    passwordCount--;
    
    return SYSTEM_OK;
}

// 密码匹配
SystemStatus PWD_Match(const uint8_t *password, uint8_t length, uint16_t *id)
{
    if (length > MAX_PASSWORD_LENGTH) {
        return SYSTEM_ERROR;
    }
    
    for (uint16_t i = 0; i < MAX_PASSWORD_COUNT; i++) {
        if (passwords[i].valid && 
            passwords[i].length == length &&
            memcmp(passwords[i].password, password, length) == 0) {
            *id = i;
            return SYSTEM_OK;
        }
    }
    
    return SYSTEM_NOT_FOUND;
}

// 修改密码
SystemStatus PWD_Modify(uint16_t id, const uint8_t *new_password, uint8_t length)
{
    if (id >= MAX_PASSWORD_COUNT || !passwords[id].valid) {
        return SYSTEM_NOT_FOUND;
    }
    
    if (length > MAX_PASSWORD_LENGTH) {
        return SYSTEM_ERROR;
    }
    
    // 更新密码
    memcpy(passwords[id].password, new_password, length);
    passwords[id].length = length;
    
    return SYSTEM_OK;
}

// 获取已注册密码数量
uint16_t PWD_GetCount(void)
{
    return passwordCount;
}

// 清空所有密码
SystemStatus PWD_Clear(void)
{
    memset(passwords, 0, sizeof(passwords));
    passwordCount = 0;
    return SYSTEM_OK;
} 